package br.sed.theenemy.presentation.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import br.sed.theenemy.business.exception.DBException;
import br.sed.theenemy.business.exception.InvalidUniqueBeanException;
import br.sed.theenemy.business.exception.InvalidUserException;
import br.sed.theenemy.business.services.Services;
import br.sed.theenemy.model.bean.User;
import br.sed.theenemy.presentation.EnemyConstants;
import br.sed.theenemy.presentation.UserSession;
import br.sed.theenemy.presentation.form.LoginForm;

/**
 * 
 * @author JulioCB
 * @email jcbjulio@gmail.com
 * 
 */
public class LoginAction extends DispatchAction{
    
	// forwards
    private static final String HOME_PAGE = "HomePage";
    private static final String LOGIN_PAGE = "LoginPage";
	
    public ActionForward unspecified(final ActionMapping mapping,
           final ActionForm form, final HttpServletRequest request, 
           final HttpServletResponse response) {
        
    	final UserSession session = new UserSession(request, false);
        final User user = session.getLoggedUser();
        //final LoginForm loginForm = (LoginForm) form;
        //configureAttemptsParams(loginForm);
        
        if (user == null) {
            // User not logged in, redirect to login.jsp
            return mapping.findForward(LOGIN_PAGE);
        } else {
            // User logged redirect to home
            return mapping.findForward(HOME_PAGE);
        }
    }  
    public ActionForward activated(final ActionMapping mapping, final ActionForm form, final HttpServletRequest request, final HttpServletResponse response) {
    	final LoginForm loginForm = (LoginForm) form;
    	loginForm.setRegister(true);
    	return mapping.findForward(LOGIN_PAGE);
    }
    public ActionForward login(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request, 
            final HttpServletResponse response) {
         
         final LoginForm loginForm = (LoginForm) form; // get the form bean
         
         // validate form; if there is an error, presents an custom message
         if (!form.validate(mapping, request).isEmpty()) {
//             final ActionErrors errors = new ActionErrors();
//             errors.add(null, new ActionMessage("form.login.err.auth"));
//             saveErrors(request, errors);
//             form.reset(mapping, request);
             loginForm.setError(true);
             return mapping.findForward(LOGIN_PAGE);
         }
           
//         final String ip = request.getRemoteAddr();
         final String email = loginForm.getEmail();
         final String password = loginForm.getPassword();

         // Tests whether the user is blocked
//         if (!adminSecurityUtil.canLogIn(ip, email)) {
//             final ActionErrors userBlockErrors = new ActionErrors();
//             userBlockErrors.add(null, new ActionMessage("form.login.err.userBlocked"));
//             saveErrors(request, userBlockErrors);
//             form.reset(mapping, request);
//             configureAttemptsParams(loginForm);
//             return mapping.findForward(LOGIN_PAGE);
//         }
         
         Services services = Services.getInstance();
         User user;

        try {
			user = services.login(email, password);
			putLoggedUserInSession(request, user);
		} catch (InvalidUserException e) {
		    loginForm.setError(true); 
        	 return mapping.findForward(LOGIN_PAGE);
		} catch (InvalidUniqueBeanException e) {
		    return mapping.findForward(EnemyConstants.ERROR_PAGE);
		} catch (DBException e) {
		    return mapping.findForward(EnemyConstants.ERROR_PAGE);
		}
             

//         catch (AuthenticationException e) {
//             adminSecurityUtil.incrementLoginAttempt(ip, email);
//             final ActionErrors authErrors = new ActionErrors();
//             authErrors.add(null, new ActionMessage("form.login.err.auth"));
//             saveErrors(request, authErrors);
//             form.reset(mapping, request);
//             configureAttemptsParams(loginForm);
//             return mapping.findForward(LOGIN_PAGE);
//         }
         
         // Forward control to the specified success target
         return (mapping.findForward(HOME_PAGE));
     }
    
    /**
     * Set the logged user in the session. According to security issues the session must be invalidated before. 
     * @param request HttpServletRequest
     * @param user logged user
     */
    private void putLoggedUserInSession(final HttpServletRequest request,
            User user) {
        
        // first invalidate the session
        UserSession session = new UserSession(request, false);
        session.invalidate();
        
        //creates a new session and set the user
        session = new UserSession(request, true);
        session.setLoggedUser(user);
    }
        
    /**
     * Logout Action.
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward next step
     */
    public ActionForward logout(final ActionMapping mapping, final ActionForm form,
              final HttpServletRequest request, final HttpServletResponse response) {

        // Get the user logged
        final UserSession session = new UserSession(request, false);
        final User user = session.getLoggedUser();

         if (user == null) {
//             if (logger.isInfoEnabled()){
//                 logger.info(AdminMessageConstants.END_USER_NOT_LOGGED);
//             }
         } else {
              // Remove the user from the session
              session.removeLoggedUser();
              session.invalidate();
              
//              if (logger.isInfoEnabled()){
//                  final String message = MessageFormat.format(AdminMessageConstants.LOGOUT_EMAIL, user.getEmail());
//                  logger.info(message);
//              }
         }
         
//         final LoginForm loginForm = (LoginForm) form;
//         configureAttemptsParams(loginForm);

         // Redirect to login
         return mapping.findForward(LOGIN_PAGE);
    }
    
    /**
     * Set max login attemps and timout attributes.
     * 
     * @param loginForm loginForm 
     */
//    private void configureAttemptsParams(final LoginForm loginForm) {
//        loginForm.setMaxLoginAttemps(adminSecurityUtil.getMaxLoginAttemps());
//        loginForm.setTimeout(adminSecurityUtil.getLoginTimeoutInMinuts());
//    }
}
